#include <iostream>
#include <cstring>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Log.hpp"

enum
{
    SOCKERR = -1,
    BINDERR,
    LISTENERR,
    ACCEPTERR,
    CONNECTERR
};

class Sock
{
public:
    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            lg(FATAL, "socket success... sockfd: %d, errno: %d, strerror: %s", _sockfd, errno, strerror(errno));
            exit(SOCKERR);
        }

        //端口和地址复用
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

    }
    void Bind(uint16_t port)
    {
        struct sockaddr_in Server;
        Server.sin_family = AF_INET;
        Server.sin_addr.s_addr = INADDR_ANY; // #define	INADDR_ANY		((in_addr_t) 0x00000000)
        Server.sin_port = htons(port);
        socklen_t len = sizeof(Server);
        int n = bind(_sockfd, (struct sockaddr *)&Server, len);
        // std::cout << _sockfd << std::endl;
        if (n < 0)
        {
            lg(FATAL, "bind fail... sockfd: %d, errno: %d, strerror: %s", _sockfd, errno, strerror(errno));
            exit(BINDERR);
        }

    }

    void Listen()
    {
        int n = listen(_sockfd, 5);
        if (n < 0)
        {
            lg(FATAL, "listen fail... sockfd: %d, errno: %d, strerror: %s", _sockfd, errno, strerror(errno));
            exit(LISTENERR);
        }
    }

    int Accept(std::string &clientip, uint16_t &clientport)
    {
        struct sockaddr_in Client;
        socklen_t len = sizeof(Client);
        int sockfd = accept(_sockfd, (struct sockaddr *)&Client, &len);
        if (sockfd < 0)
        {
            lg(FATAL, "accpet fail... sockfd: %d, errno: %d, strerror: %s", _sockfd, errno, strerror(errno));
            exit(ACCEPTERR);
        }

        char client[32];
        // 第二个参数需要传地址
        inet_ntop(AF_INET, &Client.sin_addr, client, sizeof(client));
        clientip = client;
        clientport = ntohs(Client.sin_port);

        return sockfd;
    }

    void Close()
    {
        close(_sockfd);
    }

    int Getfd()
    {
        return _sockfd;
    }

private:
    int _sockfd;
};
